<?php
if (get_magic_quotes_gpc()) {

    /**
     * 
     * @param type $value
     * @return type
     */
    function EaParseSpecialChars($value) {
        return is_array($value) ? array_map('EaParseSpecialChars', $value) : addslashes($value);
    }

    $_POST = array_map('EaParseSpecialChars', $_POST);
    $_GET = array_map('EaParseSpecialChars', $_GET);
    $_COOKIE = array_map('EaParseSpecialChars', $_COOKIE);
    $_REQUEST = array_map('EaParseSpecialChars', $_REQUEST);
}

session_start();
define('INCLUDES', dirname(__FILE__));
define('DS', DIRECTORY_SEPARATOR);
define('USUARIO', "appuserinfo");
define('DB_CHARSET', "UTF-8");
define('DATE_PATTERN_MYSQL', '%Y-%m-%d');
define('DATE_PATTERN', 'y-m-d');
define('TIME_PATTERN', 'H:i');
define('FORMAT', 'Y-m-d');

include(INCLUDES . DS . 'cfg.inc.php');
include(INCLUDES . DS . 'db.inc.php');

/**
 * 
 * @param type $number
 * @param type $message
 * @param type $file
 * @param type $line
 */
function captureErrorNormal($number, $message, $file, $line) {
    // Insert all in one table
    $error = array('type' => $number, 'message' => $message, 'file' => $file, 'line' => $line);
    // Display content $error variable
    echo '<pre>';
    print_r($error);
    echo '</pre>';
}

/**
 * gener htmlentities
 * @param type $v
 * @return type 
 */
function ea_htmlentities($v) {
    return is_array($v) ? array_map('ea_htmlentities', $v) : htmlentities($v);
}

/**
 * 
 * @param type $timeout
 */
function ea_session_check($timeout = 1440) {
    ini_set('session.gc_maxlifetime', $timeout);
    $a = session_id();
    if ($a == '') {
        ea_session_build();
    }
    if (isset($_SESSION['timeout_idle']) && $_SESSION['timeout_idle'] < time()) {
        ea_session_build(true);
        $_SESSION['safety'] = true;
    }
    if (!isset($_SESSION['safety'])) {
        ea_session_build(true);
        $_SESSION['safety'] = true;
    }
    $_SESSION['sessionid'] = session_id();
    $_SESSION['timeout_idle'] = time() + $timeout;
}

/**
 * 
 * @param type $destroy
 */
function ea_session_build($destroy = false) {
    if ($destroy) {
        session_destroy();
    }
    session_start();

    session_regenerate_id(true);
    $_SESSION = array();
}

function getMultiselectValues($v) {
    $r = $v;
    if (is_array($v)) {
        $r = "";
        foreach ($v as $i) {
            if (!empty($i)) {
                $r.=$i . ",";
            }
        }
    }
    return $r;
}

/**
 * 
 * @param type $table
 * @param type $where
 * @param type $fname
 * @param type $db
 * @return type
 */
function getFRFieldContent($table, $where, $fname, $db) {
    $c = $db->query_select($table, $where, null);
    return $c[0][$fname];
}

function myExceptionHandler($e) {
    echo "<h1>Technical error</h1>";
    echo "<pre>";
    echo $e;
    echo "</pre>";
}

/**
 *
 * @param type $theValue
 * @param type $theType
 * @param type $forLike
 * @param type $theDefinedValue
 * @param type $theNotDefinedValue
 * @return type 
 */
function sqlValue($theValue, $theType, $forLike = false, $theDefinedValue = "", $theNotDefinedValue = "") {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
    switch ($theType) {
        case "text":
            $theValue = $forLike ? '%' . $theValue . '%' : $theValue;
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
            break;
        case "int":
            $theValue = ($theValue != "") ? intval($theValue) : "NULL";
            break;
        case "float":
            $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
            break;
        case "double":
            $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
            break;
        case "date":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
            break;
        case "defined":
            $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
            break;
    }
    return $theValue;
}

/**
 *
 * @param type $str
 * @return type 
 */
function isEmpty($str) {
    return (strlen(trim($str)) == 0) || ($str == "null");
}

/**
 *
 * @param type $name
 * @param type $sep
 * @return type 
 */
function getParamArr($name, $sep = "-") {
    $arr = array();
    while ($arrPost = each($_REQUEST)) {
        $arrExplode = explode($sep, $arrPost["key"]);

        if ($arrExplode[0] == $name) {
            $arr[$arrPost["key"]] = $arrPost["value"];
        }
    }
    return $arr;
}

/**
 *
 * @param type $name
 * @param type $default
 * @return type 
 */
function getParam($name, $default = null) {
    if (array_key_exists($name, $_REQUEST)) {
        $param = $_REQUEST[$name];
        if ($default != null && isEmpty($param)) {
            return $default;
        }
        $db = DbManager::getMe();
        $param = $db->escape($param);
        return $param;
    } else
        return $default;
}

/**
 *
 * @return type 
 */
function getRowsToInsert() {
    $rows = array();
    if ($_SESSION["lastFile"] != null) {
        // instancing new CSVReader object reading a file 'sample.csv'
        $reader = new CSVReader(new FileReader($_SESSION["lastFile"]));
        // set the separator use format, here a comma
        $reader->setSeparator(',');

        while (false != ( $cell = $reader->next() )) {
            $rows[] = $cell;  //carnet,nota
        }
    }
    return $rows;
}

/**
 * Caga modulos del sistema
 * @param type $dir 
 */
function includeModules($dir) {

    if (is_dir($dir)) {
        $files = array();
        $dirs = array();

        $dh = opendir($dir);
        while (false !== ($filename = readdir($dh))) {
            if (substr($filename, 0, 1) != '.' and $filename != 'CVS') {
                $files[] = $filename;
            }
        }
        closedir($dh);

        for ($i = 0; $i < count($files); $i++) {
            if (is_dir("$dir/{$files[$i]}")) {
                $dirs[] = "$dir/{$files[$i]}";
            } elseif (is_file("$dir/{$files[$i]}") and (substr($files[$i], -4) == '.php')) {
                require_once "$dir/{$files[$i]}";
            }
        }

        foreach ($dirs as $subdir) {
            includeModules($subdir);
        }
    }
}

/**
 * agrega dias a la fecha
 * @param type $givendate
 * @param type $day
 * @param type $mth
 * @param type $yr
 * @return type 
 */
function add_date($givendate, $day = 0, $mth = 0, $yr = 0) {
    $cd = strtotime($givendate);
    $newdate = date('Y-m-d h:i:s', mktime(date('h', $cd), date('i', $cd), date('s', $cd), date('m', $cd) + $mth, date('d', $cd) + $day, date('Y', $cd) + $yr));
    return $newdate;
}

/**
 * Muestra un listado de errores
 * @param type $errors 
 */
function showError($errors) {
    ?>
    <div class="ui-widget" style="border: 0px solid white; width: 800px; height: auto; vertical-align: bottom;" align="center">
        <div class="ui-state-error ui-corner-all" style="margin-top: 0px; padding: 0pt 0.7em; height: auto; width: 450px;"> 
            <span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"></span>
            <ul>
                <?php
                foreach ($errors as $e) {
                    echo "<li><strong>$e</strong></li>";
                }
                ?>
            </ul>
        </div>
    </div>
    <?php
}

/**
 * 
 * @return string
 */
function getMesesData() {
    $meses = array(1 => "Enero", 2 => "Febrero", 3 => "Marzo", 4 => "Abril",
        5 => "Mayo", 6 => "Junio", 7 => "Julio", 8 => "Agosto", 9 => "Septiembre", 10 => "Octubre", 11 => "Noviembre",
        12 => "Diciembre");
    return $meses;
}

/**
 * Retorna listado de meses
 * @return type 
 */
function getMeses() {
    return getMesesData();
}

/**
 *
 * @return type 
 */
function getMesesSelect() {
    $str = "";
    $meses = getMesesData();
    foreach ($meses as $k => $m) {
        $str = $str + "<option value='$k'>$m</option>";
    }
    return $str;
}

/**
 * agrega variable a la session
 * @param type $key
 * @param type $val
 * @param type $ser 
 */
function addSessionVar($key, $val, $ser = false) {
    $_SESSION[$key] = $ser ? serialize($val) : $val;
}

/**
 * elimina una variable de session
 * @param type $key 
 */
function remSessionVar($key) {
    unset($_SESSION[$key]);
}

/**
 * Devuelve una variable de la session
 * @param type $key
 * @param type $unSer
 * @return type 
 */
function getSessionVar($key, $unSer = false) {
    return isset($_SESSION[$key]) ? ($unSer ? unserialize($_SESSION[$key]) : $_SESSION[$key]) : NULL;
}

/**
 * Revisa caracteresespeciales
 * @param type $value
 * @return type 
 */
function ea_dbstrip($value) {
    if (get_magic_quotes_gpc() != 0) {
        if (is_array($value))
            if (ea_array_is_associative($value)) {
                foreach ($value as $k => $v)
                    $tmp_val[$k] = stripslashes($v);
                $value = $tmp_val;
            }
            else
                for ($j = 0; $j < sizeof($value); $j++)
                    $value[$j] = stripslashes($value[$j]);
        else
            $value = stripslashes($value);
    }
    return $value;
}

function ea_load_business() {
    includeModules(BO_LIBS);
}

function ea_array_is_associative($array) {
    if (is_array($array) && !empty($array)) {
        for ($iterator = count($array) - 1; $iterator; $iterator--) {
            if (!array_key_exists($iterator, $array)) {
                return true;
            }
        }
        return !array_key_exists(0, $array);
    }
    return false;
}

/**
 * 
 * @param type $str
 * @return type
 */
function ea_ascii_to_entities($str) {
    $count = 1;
    $out = '';
    $temp = array();

    for ($i = 0, $s = strlen($str); $i < $s; $i++) {
        $ordinal = ord($str[$i]);

        if ($ordinal < 128) {
            if (count($temp) == 1) {
                $out .= '&#' . array_shift($temp) . ';';
                $count = 1;
            }

            $out .= $str[$i];
        } else {
            if (count($temp) == 0) {
                $count = ($ordinal < 224) ? 2 : 3;
            }

            $temp[] = $ordinal;

            if (count($temp) == $count) {
                $number = ($count == 3) ? (($temp['0'] % 16) * 4096) +
                        (($temp['1'] % 64) * 64) +
                        ($temp['2'] % 64) : (($temp['0'] % 32) * 64) +
                        ($temp['1'] % 64);

                $out .= '&#' . $number . ';';
                $count = 1;
                $temp = array();
            } else {
                $out .= $str[$i];
            }
        }
    }

    return $out;
}
?>